﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoAddonBiz_FreightForwarder.Cost.OpenInvoice
{
    public class B1Form_InvoiceList : SAPBoAddon.B1Form
    {
        #region override
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {

        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.FormType = B1FormTypes.ado_AVA_InvoiceList;
            FormSetting.FormFileName = FormSetting.FormType + "Form.srf";
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {

        }
        #endregion
        public B1Form_InvoiceList()
        {
            frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_InvoiceList_frm_ItemEvent);
        }
        void B1Form_InvoiceList_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                if (pVal.ItemUID == "Grid" && pVal.Row >= 0 && pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK)
                {
                    SAPbouiCOM.Grid grid = CurrentForm.Items.Item(pVal.ItemUID).Specific;
                    if (grid.Rows.IsSelected(pVal.Row))
                        grid.Rows.SelectedRows.Remove(pVal.Row);
                    else
                        grid.Rows.SelectedRows.Add(pVal.Row);
                    //CurrentForm.Items.Item(pVal.ItemUID).Specific.Rows.SelectedRows.Add(pVal.Row);
                }
                if (pVal.ItemUID == "7" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    AddConfirmBill(ref BubbleEvent);
                }
            }
            else
            {
                if (pVal.ItemUID == "6" && (pVal.EventType == SAPbouiCOM.BoEventTypes.et_KEY_DOWN || pVal.ItemChanged))
                {
                    ListFind(pVal.FormUID);
                }
            }
        }
        /// <summary>
        /// 查找指定的数据
        /// </summary>
        /// <param name="FormUID"></param>
        private void ListFind(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            string FieldName, FieldValue;

            oForm = SBOApp.Forms.Item(FormUID);
            FieldName = SAPBoAddon.B1Assistant.Item.GetValue(FormUID, "5").ToString();
            FieldValue = SAPBoAddon.B1Assistant.Item.GetValue(FormUID, "6").ToString();
            if (string.IsNullOrWhiteSpace(FieldName)) FieldName = "CardName";
            SAPBoAddon.B1Assistant.Grid.GridTableFindRow(FormUID, "Grid", "Table", FieldName, FieldValue);
        }

        /// <summary>
        /// 添加对账单信息到发票
        /// </summary>
        /// <param name="BubbleEvent"></param>
        private void AddConfirmBill(ref bool BubbleEvent)
        {
            SAPbouiCOM.Form oChildForm = default(SAPbouiCOM.Form);
            SAPbouiCOM.Grid oGrid = default(SAPbouiCOM.Grid);
            SAPbouiCOM.Form oParentForm = default(SAPbouiCOM.Form);
            SAPbouiCOM.Matrix oMtx = default(SAPbouiCOM.Matrix);
            SAPbouiCOM.DBDataSource dbds = default(SAPbouiCOM.DBDataSource);
            bool Flag = false;
            string Currency = string.Empty;
            decimal Rate = 0;
            decimal Amount = 0;
            SAPbobsCOM.Recordset rs;
            try
            {
                Flag = false;
                oChildForm = CurrentForm;
                oGrid = oChildForm.Items.Item("Grid").Specific;
                oParentForm = SBOApp.Forms.Item(oChildForm.DataSources.UserDataSources.Item("ParentUID").Value.Trim());
                oMtx = oParentForm.Items.Item("mtx_1").Specific;
                dbds = oParentForm.DataSources.DBDataSources.Item("@AVA_INV2");
                //dbds.Clear();
                SBOApp.SetStatusBarMessage("开始导入数据，请稍等......", SAPbouiCOM.BoMessageTime.bmt_Short, false);
                for (int i = 0; i <= oGrid.Rows.SelectedRows.Count - 1; i++)
                {
                    int gr = oGrid.Rows.SelectedRows.Item(i, SAPbouiCOM.BoOrderType.ot_SelectionOrder);
                    if (!oGrid.Rows.IsSelected(gr))
                        continue;
                    int Offset = SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(oParentForm, dbds, 1);

                    dbds.Offset = dbds.Size - 1;
                    dbds.SetValue("U_Direction", dbds.Offset, (oGrid.DataTable.GetValue("Direction", gr).ToString().Trim() == "应收" ? "I" : "O"));
                    dbds.SetValue("U_BaseEntry", dbds.Offset, oGrid.DataTable.GetValue("DocEntry", gr).ToString().Trim());
                    dbds.SetValue("U_CardName", dbds.Offset, oGrid.DataTable.GetValue("CardName", gr).ToString().Trim());
                    dbds.SetValue("U_Currency", dbds.Offset, oGrid.DataTable.GetValue("DocCur", gr).ToString().Trim());
                    dbds.SetValue("U_Rate", dbds.Offset, oGrid.DataTable.GetValue("DocRate", gr).ToString().Trim());
                    dbds.SetValue("U_Amount", dbds.Offset, oGrid.DataTable.GetValue("Amount", gr).ToString().Trim());//开票金额
                    Currency = oGrid.DataTable.GetValue("DocCur", gr).ToString().Trim();
                    Rate = Convert.ToDecimal(oGrid.DataTable.GetValue("DocRate", gr).ToString().Trim());// Utils.GetRateByCurrency(Currency);
                    Amount += (oGrid.DataTable.GetValue("Direction", gr).ToString().Trim() == "应收" ? Convert.ToDecimal(oGrid.DataTable.GetValue("Amount", gr).ToString().Trim()) : -Convert.ToDecimal(oGrid.DataTable.GetValue("Amount", gr).ToString().Trim()));
                    Flag = true;
                    #region 选择发票类型
                    //发票类型
                    rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                    rs.DoQuery("SELECT U_InvoiceType FROM [ODRF] Where DocEntry = " + oGrid.DataTable.GetValue("DocEntry", gr).ToString().Trim());
                    if (rs.RecordCount > 0)
                    {
                        string InvType = string.Empty;
                        InvType = rs.Fields.Item("U_InvoiceType").Value;
                        if (string.IsNullOrEmpty(InvType) == false)
                        {
                            if (oParentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("U_InvoiceTaxType", 0).Trim() != "")
                            {
                                oParentForm.DataSources.DBDataSources.Item("@AVA_OINV").SetValue("U_InvoiceTaxType", 0, InvType);
                            }
                            else
                            {
                                if (InvType != oParentForm.DataSources.DBDataSources.Item("@AVA_OINV").GetValue("U_InvoiceTaxType", 0).Trim())
                                {
                                    if (SBOApp.MessageBox("新添加了开票类型和原来的发票类型不一样，是否选择新的？", 1, "原类型", "新类型") == 2)
                                    {
                                        oParentForm.DataSources.DBDataSources.Item("@AVA_OINV").SetValue("U_InvoiceTaxType", 0, InvType);
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
                if (Flag == false)
                {
                    BubbleEvent = false;
                }
                oParentForm.DataSources.UserDataSources.Item("Amount").Value = (Convert.ToDecimal(oParentForm.DataSources.UserDataSources.Item("Amount").Value) + Amount).ToString();
                oParentForm.DataSources.UserDataSources.Item("Currency").Value = Currency;
                oParentForm.DataSources.DBDataSources.Item("@AVA_OINV").SetValue("U_Rate", 0, Rate.ToString());
                //oParentForm.DataSources.UserDataSources.Item("Rate").Value = Rate.ToString();

                oMtx.LoadFromDataSource();
                if (oParentForm.Mode != SAPbouiCOM.BoFormMode.fm_ADD_MODE && oParentForm.Mode != SAPbouiCOM.BoFormMode.fm_UPDATE_MODE) oParentForm.Mode = SAPbouiCOM.BoFormMode.fm_UPDATE_MODE;
                SBOApp.SetStatusBarMessage("导入完成", SAPbouiCOM.BoMessageTime.bmt_Short, false);
                oChildForm.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
